import fs from "fs";
import {exec} from "@/utils/main/cmd.shell.utils";
import * as path from "path";
import {noticeMessageToRenderer, noticeTriggerStore} from "@/electron/helper";

/**
 * 根据 git 文件夹获取远程地址
 * @param dir   git文件夹
 */
export const getGitAddress = async (dir) => {
    const p = path.resolve(dir);
    if (!fs.existsSync(p)) return 'path is not exist!';
    const res = await exec(`git -C "${p}" remote -v`);
    return res.message.match(/https?:\/\/\S+/)[0];
}

/**
 * 添加提交和同步
 * @param dir
 */

let committing = false;
let pulling = false;

export const gitPull = async (dir) => {
    if (pulling) return;
    pulling = true;
    try {
        const p = path.resolve(dir);
        const pullRes = await exec(`git -C "${p}" pull`);
        if (!pullRes) {
            noticeMessageToRenderer("获取服务器版本失败！", false);
            return false;
        }
    } finally {
        pulling = false;
    }
    return true;
}

export const commitAndPush = async (dir) => {
    if (committing) return;
    console.log(dir);
    committing = true;
    try {
        noticeTriggerStore("setGitSync", 'dispatch', true);
        const p = path.resolve(dir);
        const addRes = await exec(`git -C "${p}" add .`);
        if (!addRes) {
            noticeMessageToRenderer("添加文件失败", false)
            return false;
        }
        const commitRes = await exec(`git -C "${p}" commit -m 'backup'`);
        if (!commitRes) {
            noticeMessageToRenderer("提交失败！", false)
            return false;
        }
        const pushRes = await exec(`git -C "${p}" push --force`);
        if (!pushRes) {
            noticeMessageToRenderer("推送失败", false)
            return false;
        }
        // noticeMessageToRenderer("同步完成！", true);
        return true;
    } finally {
        committing = false;
        console.log(112123123213);
        noticeTriggerStore("setGitSync", 'dispatch', false);
    }

}